#include "./inc/cpp.h"
#include <chrono>
#include <thread>
#include <atomic>
#include <map>

namespace demo_sdk {

/* ---------- 全局管理 ---------- */
static std::atomic<int64_t> g_listen_id{0};
static std::map<int64_t, IMessageObserver*> g_observers;

/* ---------- MySDK 实现 ---------- */
int64_t MySDK::listen(const std::string& topic, IMessageObserver* observer) {
    if (!observer) return -1;

    int64_t id = ++g_listen_id;
    g_observers[id] = observer;

    // 模拟异步收到消息
    std::thread([id, topic]() {
        std::this_thread::sleep_for(std::chrono::milliseconds(300));
        auto it = g_observers.find(id);
        if (it != g_observers.end()) {
            Message msg{1, "hello from topic: " + topic,
                        std::chrono::system_clock::now().time_since_epoch().count()};
            it->second->onMessage(msg);
        }
    }).detach();

    return id;
}

void MySDK::stop(int64_t listen_id) {
    auto it = g_observers.find(listen_id);
    if (it != g_observers.end()) {
        it->second->onError(0); // 通知停止
        g_observers.erase(it);
    }
}

const char* MySDK::getVersion() {
    return "1.0.0";
}

} // namespace demo_sdk